/*
 * This file is part of the Boring Engine.
 *
 * Copyright (c) 2011 by pf5234 <pf5234@users.sourceforge.net>.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.googlecode.boringengine;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Scanner;

public class Animator {

    private static HashMap<String, Animator> cache = new HashMap<String, Animator>();
    private HashMap<String, AnimInfo> anims;
    private String defaultName;
    private AnimInfo current;
    private int frameCount;
    private boolean paused;

    public Animator(String animName, GameLoader loader) {
        if (cache.containsKey(animName)) {
            Animator a = cache.get(animName);
            anims = a.anims;
            defaultName = a.defaultName;
            current = anims.get(defaultName);
            return;
        }
        Log.debug("Processing '%s'...", animName);
        anims = new HashMap<String, AnimInfo>();
        String line;
        InputStream in = loader.getFile(animName + ".anim");
        if (in == null) {
            Log.error("File %s not found", animName);
            return;
        }
        Scanner input = new Scanner(in);
        line = input.nextLine();
        if (line.startsWith("default")) {
            String[] tmp = line.split(" ");
            defaultName = tmp[1];
            line = input.nextLine();
        }
        while (input.hasNextLine()) {
            String[] tmp = line.split(" ");
            if (defaultName == null) defaultName = tmp[0];
            AnimInfo info = new AnimInfo();
            info.name = tmp[0];
            info.nextTarget = tmp[1];
            info.nextFrame = Integer.parseInt(tmp[2]);
            if (tmp.length >= 5) {
                info.moveX = Integer.parseInt(tmp[3]);
                info.moveY = Integer.parseInt(tmp[4]);
            }
            String spriteStr = "";
            int w = 0, h = 0;
            while (input.hasNextLine()) {
                line = input.nextLine();
                if (!Character.isDigit(line.charAt(0)) && line.charAt(0) != '.')
                    break;
                w = line.length();
                h++;
                spriteStr += line;
            }
            info.sprite = Render.createSprite(spriteStr, w, h);
            anims.put(info.name, info);
        }
        if (!anims.containsKey(defaultName)) {
            String str = anims.keySet().iterator().next();
            Log.error("Default animation '%s' does not exist, using '%s' instead", defaultName, str);
            defaultName = str;
        }
        current = anims.get(defaultName);
        cache.put(animName, this);
    }

    public void draw(int x, int y) {
        draw(x, y, false);
    }

    public void draw(int x, int y, boolean flip) {
        if (current == null) return;
        int oldx = Render.getX(), oldy = Render.getY();
        boolean oldflip = Render.isFlipped();
        Render.moveOverWithoutScale(x-current.moveX, y-current.moveY);
        Render.addFlip(flip);
        Render.drawSprite(current.sprite);
        Render.setFlip(oldflip);
        Render.setPosition(oldx, oldy);
        if (paused) return;
        frameCount++;
        if (frameCount > current.nextFrame) {
            if (current.isOrphan || !anims.containsKey(current.nextTarget)) {
                if (!current.isOrphan) {
                    Log.error("Animation '%s' points to '%s', which is not valid",
                            current.name, current.nextTarget);
                    current.isOrphan = true;
                }
                current = anims.get(defaultName);
            } else
                current = anims.get(current.nextTarget);
            frameCount = 0;
        }
    }

    public void changeAnimation(String name) {
        if (!anims.containsKey(name)) {
            Log.error("Animation '%s' is not valid", name);
            current = anims.get(defaultName);
        } else
            current = anims.get(name);
        frameCount = 0;
    }
    
    public boolean isPaused() {
        return paused;
    }

    public void setPaused(boolean p) {
        paused = p;
    }
    
    public void clearCache() {
        cache.clear();
    }

    private class AnimInfo {
        String name, nextTarget;
        int nextFrame, moveX, moveY;
        Sprite sprite;
        boolean isOrphan;
    }
}
